package com.syl.auth.loginlogic;

import com.syl.auth.loginlogic.base.AbstractLoginLogic;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @ClassName LoginLogicFactory
 * @Description 登陆逻辑工厂
 * @Author YunLong
 * @Date 2023/4/27 22:01
 */
@Component
@Slf4j
public class LoginLogicFactory {

    @Resource
    List<AbstractLoginLogic> loginLogicList;

    public Map<String, AbstractLoginLogic> loginLogicMap = new ConcurrentHashMap<>();

    public AbstractLoginLogic getLoginLogic(String value) {
        return Optional.ofNullable(loginLogicMap.get(value)).orElseGet(() -> {
            log.error("未获取到登录逻辑。logType:{}", value);
            throw new AuthenticationServiceException("无此登录逻辑。logType:" + value);
        });
    }

    @PostConstruct
    public void init() {
        loginLogicList.forEach(loginLogic ->
                loginLogicMap.put(loginLogic.getSupportLoginType(), loginLogic));
        log.debug("登录逻辑类装载完毕。load login type:{}", loginLogicMap.keySet());
    }
}
